package com.and9.mchen.mweather.cw.demo



class GXMLData {

	def static String getXMLData(String key){
		def urlString="http://flash.weather.com.cn/wmaps/xml/${key}.xml"
		def stream=new URL(urlString).openStream();
		def br=new BufferedReader(new InputStreamReader(stream,"utf-8"));
		def sb=new StringBuilder();
		def temp=null;
		
		while((temp=br.readLine())!=null){
			sb.append("${temp}\n");
		}
		
		return sb.toString();
	}
	
	def static List<Local> getCityByProvince(){
		def local=getProvinceLocal();
		def provinces=local.getChildren();
		
		for(Local province in provinces){
			def xmlData=getXMLData(province.getPinyin());
			province.setChildren([]);
			if(!xmlData.startsWith("<!DOCTYPE")){
				def root=new XmlParser().parseText(xmlData);
				for(def it in root.city){
					Local child=new Local();
					child.setName(it?.attribute("cityname"));
					child.setPinyin(it?.attribute("pyName"));
					child.setLocalCode(it?.attribute("url"));
					province.setChildren(province.getChildren() << child);
				}
			}
			
		}
		
		return provinces;
		
	}
	
	def static List<Local> getOtherCityTwon(){
		List<Local> privinces=getCityByProvince()[27] as List;
		def list=[];
		for(def local in privinces){
			def childLocal=local.getChildren();
			for(def child in childLocal){
				def xmlData=getXMLData(child.getPinyin());
				child.setChildren([]);
				if(!xmlData.startsWith("<!DOCTYPE")){
					def root=new XmlParser().parseText(xmlData);
					for(def it in root.city){
						Local c=new Local();
						c.setName(it?.attribute("cityname"));
						c.setLocalCode(it?.attribute("url"));
						child.setChildren(child.getChildren() << c);
					}
				}
				list << child;
			}
		}
		return list;
	}

	def static Local getProvinceWithCity(String py, long id){
			Local local=new Local();
			local.setPinyin(py);
			local.setId(id);
			local.setChildren([]);
			def xmlData=getXMLData(local.getPinyin());
			if(!xmlData.startsWith("<!DOCTYPE")){
				def root=new XmlParser().parseText(xmlData);
				for(def it in root.city){
					Local child=new Local();
					child.setName(it?.attribute("cityname"));
					child.setPinyin(it?.attribute("pyName"));
					local.setChildren(local.getChildren() << child);
				}
			}
			return local;
	}
	
	
	def static Local getProvinceLocal(){
		def xmlData=getXMLData("china");
		Local local=new Local();
		local.setName("中国");
		local.setId(1);
		local.setChildren([]);
		def root=new XmlParser().parseText(xmlData);
		def i=1;
		for(def it in root.city){
			Local child=new Local();
			child.setName(it?.attribute("quName"));
			child.setPinyin(it?.attribute("pyName"));
			child.setId(++i);
			local.setChildren(local.getChildren() << child);
		}
		return local;
	}
	
	
}
